<template>
  <div class="city page-cover">

    <div class="top">
      <!-- 搜索 -->
      <van-search ref="search" v-model="searchValue" placeholder="城市/区域/位置" shape="round" show-action @search="onSearch"
        @cancel="onCancel" />

      <!-- tab -->
      <van-tabs v-model:active="tabActive">
        <van-tab v-for="(val, key) in allCities" :key="val.title" :title="val.title" :name="key">
        </van-tab>
      </van-tabs>
    </div>

    <!-- 列表 -->
    <div class="content">
      <!-- <van-index-bar :index-list="indexList"> -->
      <van-index-bar>
        <van-index-anchor index="热门" />
        <div class="hot-city-content">
          <span v-for="item in curGroup?.hotCities" :key="item.cityId" @click="hotCityClick(item)">{{ item.cityName }}</span>
        </div>

        <template v-for="(item, index) in curGroup?.cities" :key="index">
          <van-index-anchor :index="item.group" />
          <van-cell v-for="city in item.cities" :key="city.cityId" :title="city.cityName" @click="hotCityClick(city)"/>
        </template>
      </van-index-bar>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, toRef } from 'vue'
import { useRouter } from 'vue-router';
import { useCityStore } from '@/stores/city.js'
import { storeToRefs } from 'pinia';

const router = useRouter()

// 1.搜索
const searchValue = ref('');
function onSearch() {
  alert('input')
}
function onCancel() {
  router.back()
}

// 2.tab
const tabActive = ref(0)
// 获取pinia仓库实例
const cityStore = useCityStore()
// 发送请求
cityStore.fetchAllCities()
const { allCities } = storeToRefs(cityStore)


// 3.列表
const curGroup = computed(() => allCities.value[tabActive.value])
console.log(curGroup);
console.log(curGroup.value);
// 自定义索引列表
const indexList = computed(() => {
  const list = curGroup.value.cities.map(item => item.group)
  list.unshift("#")
  return list
})
console.log('indexList', indexList);
// 城市点击
function hotCityClick(city){
  console.log(city);
  router.back()
  cityStore.curCity = city
}

</script>

<style scoped lang="less">
.top {
  position: relative;
  z-index: 3;
}

.content {
  height: calc(100vh - 98px);
  overflow: auto;

  .hot-city-content {
    display: flex;
    flex-wrap: wrap;
    padding-left: 8px;

    span {
      width: 70px;
      height: 30px;
      border: 1px solid #ccc;
      border-radius: 10px;
      text-align: center;
      line-height: 30px;
      margin: 8px;
    }
  }
}
</style>
